let express = require("express");
let router = express.Router();
let mongoose = require('mongoose');
let jsonwebtoken = require('jsonwebtoken')
require('../util/authConfig')

router.get('/query', async function (req, resp) {
    //获取请求头中的token数据
    let auth = req.header('Authorization');
    let token = auth.replace('Bearer ', '');
    // userObj为student信息
    let userObj = jsonwebtoken.verify(token, 'star').user;
    //获取试卷信息
    let re = await mongoose.model('collectionsModel').find({
        studentId: userObj._id
    }).populate('studentId').populate({
        path: 'exerciseId',
        populate: {
            path: 'pointId'
        }
    })
    //判断请求结果
    if (re) {
        resp.send({
            code: 1,
            message: '获取收藏夹题目成功',
            data: re
        })
    } else {
        resp.send({
            code: 2,
            message: '请求收藏夹题目失败'
        })
    }
})


//删除题目
router.post('/delete', async function (req, resp) {
    let { collectionId } = req.body;
    let re1 = await mongoose.model('collectionsModel').deleteMany({
        _id: collectionId
    });
    let re2 = await mongoose.model('collectionsModel').find({
        studentId: userObj._id
    }).populate({
        path: 'exerciseId',
        populate: {
            path: 'pointId'
        }
    })

    if (re1 && re2) {
        resp.send({
            code: 1,
            message: '已删除用户收藏题',
            data: re2
        })
    } else {
        resp.send({
            code: 2,
            message: '收藏题目删除失败'
        })
    }

});


//增加收藏
router.post('/add',async function(req,resp){
    let {studentId,exerciseId}=req.body;

    let re = await mongoose.model('collectionsModel').find({
        studentId:studentId,
        exerciseId:exerciseId
    });
    if(re.length>0){
        resp.send({
            code:1,
            message:'收藏夹中已存在此题'
        })
    }else{
        re1=await mongoose.model('collectionsModel').create(req.body);
        resp.send({
            code:2,
            message:'添加成功',
            data:re1
        })
    }
})

module.exports = router;